package com.mofang.powerdekorhelper.activity.activity;

import android.app.Dialog;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.mofang.powerdekorhelper.R;
import com.mofang.powerdekorhelper.activity.order.OrderEditActivity;
import com.mofang.powerdekorhelper.adapter.ActivityCuponAdapter;
import com.mofang.powerdekorhelper.base.MvpActivity;
import com.mofang.powerdekorhelper.base.recycleview.BaseRecycleViewList;
import com.mofang.powerdekorhelper.model.ActivityProcess;
import com.mofang.powerdekorhelper.model.CreateOrder;
import com.mofang.powerdekorhelper.model.OrderDetial;
import com.mofang.powerdekorhelper.model.ResultMessage;
import com.mofang.powerdekorhelper.persenter.ProcessPersenter;
import com.mofang.powerdekorhelper.utils.DialogUtils;
import com.mofang.powerdekorhelper.utils.GlideLoader;
import com.mofang.powerdekorhelper.utils.LoadPrograss;
import com.mofang.powerdekorhelper.utils.ParamsUtils;
import com.mofang.powerdekorhelper.utils.SharePerforenceUtils;
import com.mofang.powerdekorhelper.utils.T;
import com.mofang.powerdekorhelper.view.ProcessView;
import com.mofang.powerdekorhelper.witget.MySwipeRefreshLayout;
import com.mofang.powerdekorhelper.witget.TitleBar;

import butterknife.BindView;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by luofei on 2017/8/26 0026.
 * 说明：活动流程
 */

public class ProcessActivity extends MvpActivity<ProcessView, ProcessPersenter> implements
        ProcessView, ActivityCuponAdapter.IListOnclick, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.activity_process_titlebar)
    TitleBar mTitleBar;

    @BindView(R.id.activity_process_customer_name)
    TextView customerNameTv;

    @BindView(R.id.activity_process_customer_phone)
    TextView phoneTv;

    @BindView(R.id.process_activity_name_tv)
    TextView activityNameTv;

    @BindView(R.id.process_sign_in_tv)
    TextView signInGiftTv;

    @BindView(R.id.activity_process_price)
    TextView priceTv;

    @BindView(R.id.activity_process_sign_in)
    TextView signInTv;

    @BindView(R.id.activity_process_sure_btn)
    TextView sureBuyTv;

    @BindView(R.id.activity_process_generate_order)
    TextView generateOrderTv;

    @BindView(R.id.avtivity_process_imv)
    ImageView avtivityImv;

    @BindView(R.id.activity_process_coupons_list)
    BaseRecycleViewList couponsList;

    @BindView(R.id.activity_process_refresh)
    MySwipeRefreshLayout refreshLayout;

    @BindView(R.id.activity_process_scrollview)
    ScrollView mScrollView;

    String customerPhone = "";

    String orderCode = "";

    private LoadPrograss loadPrograss;

    private Dialog generateDialog;
    private Dialog loadDialog;

    private Integer activityId;
    private Integer customerId;
    private Integer signState;
    private String signGift;
    private String customerName;
    private Integer shopId;
    private Integer sellerId;

    @Override
    public void initView() {

        inflateLayout(R.layout.activity_process_layout);
        initTitleBarWithback(mTitleBar, R.string.activity_procress);

        couponsList.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

        refreshLayout.setOnRefreshListener(this);
        loadPrograss = new LoadPrograss(this);
    }

    @Override
    public void initData() {
        // customerId activityId 通过小程序获取
        shopId = SharePerforenceUtils.getInstance(this).getShopId();
        sellerId = SharePerforenceUtils.getInstance(this).getUserID();
        customerId = getIntent().getIntExtra("CustomerId", -1);
        activityId = getIntent().getIntExtra("ActivityId", -1);
        presenter.getActivityProcess(customerId, activityId, sellerId, shopId);
    }

    @Override
    public void setCheckOrder(OrderDetial orderDetial) {

        if (orderDetial.getCode().equals("2")) {
            toast(orderDetial.getMessage());
        } else {
            if (orderDetial.getResult() != null) {
                startActivityForResult(new Intent(ProcessActivity.this, OrderEditActivity.class)
                        .putExtra("EnterFlag", 1)
                        .putExtra("enterFlag2", 1)
                        .putExtra("IsEditState", true)
                        .putExtra("OrderCode", orderDetial.getResult().getOrderCode())
                        .putExtra("ActivityId", activityId)
                        .putExtra("CustomerId", customerId)
                        .putExtra("CustomerName", customerName)
                        .putExtra("CustomerPhone", customerPhone), ToOrderEditCode);
            } else {
                toast("订单号无法匹配请重新输入");
            }
        }

        hideProgress();
    }

    public static int ToOrderEditCode = 111;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ToOrderEditCode) {

            presenter.getActivityProcess(customerId, activityId, sellerId, shopId);
            mScrollView.scrollTo(0, 0);
        }
    }

    @Override
    public void onRefresh() {
        presenter.getActivityProcess(customerId, activityId, sellerId, shopId);
    }

    @Override
    public void setActivityProcess(ActivityProcess activityProcess) {

        signState = activityProcess.getResult().getSign_state();
        // 签到状态
        if (signState != null) {
            if (signState == 1) {
                signInTv.setText("已签到");
                signInTv.setEnabled(false);
                signInTv.setBackgroundResource(R.drawable.btn_enable_bg);
                signInTv.setPadding(15, 10, 15, 10);
            }
        }

        Integer buyState = activityProcess.getResult().getCard();
        // 购买状态
        if (buyState != null) {
            if (buyState == 1) {
                sureBuyTv.setText("已购买");
                sureBuyTv.setEnabled(false);
                sureBuyTv.setBackgroundResource(R.drawable.btn_enable_bg);
                sureBuyTv.setPadding(15, 10, 15, 10);
            }
        }

        String imageUrl = activityProcess.getResult().getBlockurl();
        if (imageUrl != null && !imageUrl.equals("")) {
            GlideLoader.getInstance(this).loadImage(imageUrl, avtivityImv);
        }

        // List<ActivityProcess.Sigogift> sigogifts = activityProcess.getResult().getSigogift();

        if (activityProcess.getResult().getSigogift() != null) {
            if (activityProcess.getResult().getSigogift().size() > 0) {
                if (activityProcess.getResult().getSigogift().get(0) != null) {
                    signInGiftTv.setText(activityProcess.getResult().getSigogift().get(0).getName());
                }
            }
        } else {
            signInGiftTv.setText("无");
        }


        customerName = activityProcess.getResult().getCustomer_name();
        customerNameTv.setText(customerName);
        activityNameTv.setText(activityProcess.getResult().getName());
        customerPhone = activityProcess.getResult().getPhone();

        phoneTv.setText(customerPhone);
        priceTv.setText((int) activityProcess.getResult().getDeposit_price() + "");

        ActivityCuponAdapter adapter = new ActivityCuponAdapter(activityProcess.getResult().getItmes(), this, R.layout.activity_coupons_list_item_layout);
        adapter.setiListOnclick(this);
        adapter.setRule(activityProcess.getResult().getEgggift(), activityProcess.getResult().getTicketgift());
        couponsList.setAdapter(adapter);

        hideProgress();
    }

    DialogUtils dialogUtils = DialogUtils.getInstance();

    // 核销卡券

    @Override
    public void offCoupons(Integer couponId, Integer giftId, String gift, Integer status) {

        dialogUtils.showCustomDialog(this, "提示", "确定核销", "确 定", "取 消",
                new MySweetAlertDialogListener1(couponId, giftId, gift, status),
                new MySweetAlertDialogListener2());
    }

    // 使用卡券
    @Override
    public void userCard(Integer couponId, Integer status) {
        presenter.getOffCoupons(couponId, null, activityId, null, status);
    }

    class MySweetAlertDialogListener1 implements SweetAlertDialog.OnSweetClickListener {
        Integer couponId;
        Integer giftId;
        Integer status;
        String gift;

        public MySweetAlertDialogListener1(Integer couponId, Integer giftId, String gift, Integer status) {
            this.couponId = couponId;
            this.giftId = giftId;
            this.gift = gift;
            this.status = status;
        }

        @Override
        public void onClick(SweetAlertDialog sweetAlertDialog) {
            presenter.getOffCoupons(couponId, giftId, activityId, gift, status);
            sweetAlertDialog.dismiss();
        }
    }

    class MySweetAlertDialogListener2 implements SweetAlertDialog.OnSweetClickListener {
        @Override
        public void onClick(SweetAlertDialog sweetAlertDialog) {
            sweetAlertDialog.dismiss();
        }
    }

    // 核销结果
    @Override
    public void setOffOrder(ResultMessage resultMessage) {
        hideProgress();
        //toast("核销成功");
        presenter.getActivityProcess(customerId, activityId, sellerId, shopId);
    }

    @Override
    public void setSign(ResultMessage resultMessage) {
        hideProgress();
        toast("签到成功");
        presenter.getActivityProcess(customerId, activityId, sellerId, shopId);
    }

    @Override
    public void setBuySure(ResultMessage resultMessage) {
        hideProgress();
        toast("购买成功");
        presenter.getActivityProcess(customerId, activityId, sellerId, shopId);
    }

    @OnClick({R.id.activity_process_sign_in, R.id.activity_process_sure_btn, R.id.activity_process_generate_order})
    void OnClick(View view) {

        switch (view.getId()) {

            case R.id.activity_process_sign_in:

                signState = 1;
                signGift = signInGiftTv.getText().toString();
                presenter.getSignUp(customerId, activityId, signState, signGift);
                break;

            case R.id.activity_process_sure_btn:

                Integer card = 1;
                presenter.getSureBuy(customerId, activityId, card);
                break;

            case R.id.activity_process_generate_order:

                orderCode = "";
                presenter.getCreateOrder(customerPhone, orderCode);

                DialogUtils.getInstance().createLoadingDialog(ProcessActivity.this, "正在生成订单，请稍候");
                break;
        }
    }

    // 生成订单
    @Override
    public void setCreateOrder(CreateOrder createOrder) {

        if (createOrder.getResult() != null) {
            orderCode = createOrder.getResult().getOrderBillNo();
            if (generateDialog != null && generateDialog.isShowing()) {
                generateDialog.dismiss();
            }
        } else {
            if (createOrder.getCode().equals("2")) {
                toast(createOrder.getMessage());
            } else {
                toast("订单号无法匹配请重新输入");
            }
            createOrder = null;
            if (generateDialog != null) {
                generateDialog.dismiss();
            }
        }

        hideProgress();

        generateDialog = new DialogUtils().GenerateOrderDialog(this, createOrder, new DialogUtils.IGenerateOrder() {

            @Override
            public void getOrderCode(String orderCode, String name, String phone) {

                // 确定
                if (!orderCode.equals("")) {

                    generateDialog.dismiss();

                    presenter.getCheckOrder(ParamsUtils.getcheckOrderParams(orderCode, activityId, shopId, customerId));

                } else {
                    toast("订单号为空无法生成订单");
                }
            }

            @Override
            public void onRefresh(String orderCode) {
                // 刷新
                // generateDialog.dismiss();

                presenter.getCreateOrder("", orderCode);

                DialogUtils.getInstance().createLoadingDialog(ProcessActivity.this, "正在生成订单，请稍候");
            }

            @Override
            public void cancleDialog() {
                // 取消
                generateDialog.dismiss();
            }

        });

        generateDialog.show();
        // }

        //hideProgress();
    }

    @Override
    public void showProgress() {
        loadPrograss.show();
    }

    @Override
    public void hideProgress() {
        refreshLayout.hide();
        loadPrograss.hide();
        DialogUtils.getInstance().hideLoadingDialog();
    }

    @Override
    public void toast(CharSequence s) {
        T.showShort(this, s);
    }

    @Override
    public void toast(int id) {

    }

    @Override
    public void showNullLayout() {
        if (generateDialog != null) {
            generateDialog.dismiss();
        }
        signInTv.setEnabled(false);
        sureBuyTv.setEnabled(false);
        generateOrderTv.setEnabled(false);
        hideProgress();
    }

    @Override
    public void hideNullLayout() {

    }

    @Override
    public void showErrorLayout(View.OnClickListener listener) {

    }

    @Override
    public void hideErrorLayout() {
        hideProgress();
    }

    @Override
    public void onError(String errorInfo) {
        hideProgress();
        toast(errorInfo);
    }

    @Override
    public ProcessPersenter initPresenter() {
        return new ProcessPersenter();
    }

}
